package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 配置订单未付款超过15分钟自动设置为状态为已取消
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void overduePayment() {
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = ordersMapper.overduePayment(Orders.PENDING_PAYMENT, time);
        if (orders != null && orders.size() > 0 ) {
            orders.forEach(
                    order -> {
                        order.setStatus(Orders.CANCELLED);
                        order.setCancelReason("用户超时未付款");
                        order.setCancelTime(LocalDateTime.now());
                        ordersMapper.update(order);
                    }
            );
            log.info("处理未付款订单");
        }

    }

    /**
     * 配置订单每天一点处理未点已送达
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void timeOrdersDaily() {
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> orders = ordersMapper.timeOrdersDaily(Orders.COMPLETED, time);
        if (orders != null && orders.size() > 0 ) {
            orders.forEach(
                    order -> {
                        order.setStatus(Orders.COMPLETED);
                        order.setDeliveryTime(time);
                        ordersMapper.update(order);
                    }
            );
            log.info("处理商家未点送达订单");
        }
    }

}
